package com.ljl.service.impl;

import com.ljl.entity.Account;
import com.ljl.service.FytxService;
import com.ljl.service.dto.SignInResultDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author 刘家良
 * @date 2022/09/11 11:24
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FytxServiceImpl implements FytxService {

    private final RestTemplate restTemplate;
    private final String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36";

    @Override
    public String login(Account account) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set(HttpHeaders.USER_AGENT, userAgent);
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("fastloginfield", "username");
        body.add("username", account.getUsername());
        body.add("password", account.getPassword());
        body.add("quickforward", "yes");
        body.add("handlekey", "ls");
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, headers);
        String loginUrl = "http://bbs.fytxonline.com/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1";
        ResponseEntity<String> response = restTemplate.postForEntity(loginUrl, httpEntity, String.class);
        List<String> strings = response.getHeaders().get("Set-Cookie");
        if (strings != null) {
            List<String> list = response.getHeaders().getValuesAsList("Set-Cookie");
            Map<String, String> map = new HashMap<>();
            list.forEach(item -> {
                if (item.startsWith("DsTB") || item.startsWith("PHPSESSID")) {
                    int indexOf = item.indexOf(";");
                    String[] split = item.substring(0, indexOf).split("=");
                    map.put(split[0], split[1]);
                }
            });
            String cookie = resolveCookie(map);
            headers.set(HttpHeaders.COOKIE, cookie);
            httpEntity = new HttpEntity<>(body, headers);
            ResponseEntity<String> response2;
            int retry = 3;
            for (int i = 0; i < retry; i++) {
                response2 = restTemplate.postForEntity(loginUrl, httpEntity, String.class);
                //重试登录
                if (!Objects.requireNonNull(response2.getBody()).contains("欢迎您回来")) {
                    List<String> list2 = response2.getHeaders().getValuesAsList("Set-Cookie");
                    list2.forEach(item -> {
                        if (item.startsWith("DsTB") || item.startsWith("PHPSESSID")) {
                            int indexOf = item.indexOf(";");
                            String[] split = item.substring(0, indexOf).split("=");
                            map.put(split[0], split[1]);
                        }
                    });
                    cookie = resolveCookie(map);
                    headers.set(HttpHeaders.COOKIE, cookie);
                    httpEntity = new HttpEntity<>(body, headers);
                }else {
                    return cookie;
                }
            }
        }
        return null;
    }

    @Override
    public String resolveFormHash(String cookie) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.COOKIE, cookie);
        headers.set(HttpHeaders.USER_AGENT, userAgent);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(null, headers);
        String homeUrl = "http://bbs.fytxonline.com/plugin.php?id=gsignin:index";
        ResponseEntity<String> response = restTemplate.exchange(homeUrl, HttpMethod.GET, httpEntity, String.class);
        int indexOf = Objects.requireNonNull(response.getBody()).indexOf(">退出</a>");
        if (indexOf != -1) {
            return response.getBody().substring(indexOf- 9, indexOf - 1);
        }
        return null;
    }

    @Override
    public SignInResultDto signIn(String cookie, String formHash) {
        SignInResultDto resultDto = new SignInResultDto();
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.COOKIE, cookie);
            headers.set(HttpHeaders.USER_AGENT, userAgent);
            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(null, headers);
            String signInUrl = "http://bbs.fytxonline.com/plugin.php";
            ResponseEntity<String> response = restTemplate.exchange(signInUrl + "?id=gsignin:index&action=signin&formhash=" + formHash, HttpMethod.GET, httpEntity, String.class);
            if (Objects.requireNonNull(response.getBody()).contains("签到成功")) {
                resultDto.setSuccess(true);
            }
            resultDto.setDetail(response.getBody());
        }catch (Exception e){
            resultDto.setDetail(e.getMessage());
        }
        return resultDto;
    }

    private String resolveCookie(Map<String, String> headers) {
        StringBuilder res = new StringBuilder();
        Set<String> strings = headers.keySet();
        for (String string : strings) {
            res.append(string).append("=").append(headers.get(string)).append(";");
        }
        return res.toString();
    }
}
